package cn.com.connext.scrm.web.rest;

import cn.com.connext.scrm.domain.master.PrizeCode;
import cn.com.connext.scrm.domain.master.PrizeGood;
import cn.com.connext.scrm.service.PrizeGoodService;
import cn.com.connext.scrm.service.UploadCodeService;
import cn.com.connext.scrm.service.dto.DwaConvertCodeModel;
import cn.com.connext.scrm.service.dto.JsonResult;
import cn.com.connext.scrm.utils.EasyExcelUtil;
import cn.com.connext.scrm.utils.ExcelUtil;
import cn.com.connext.scrm.web.rest.vm.CodeTemplateVm;
import cn.com.connext.scrm.web.rest.vm.CodeVM;
import org.hibernate.annotations.Synchronize;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import scala.Int;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 2 * @Author: shawn
 * 3 * @Date: 2020/8/11 4:05 下午
 * 4
 */
@RestController
@RequestMapping("/api/uploadCode/")
public class UploadCodeResource {

   private final Logger log = LoggerFactory.getLogger(UploadCodeResource.class);
//
    @Autowired
   private UploadCodeService uploadCodeService;
    @Autowired
   private PrizeGoodService prizeGoodService;

    private Lock lock = new ReentrantLock();

    /**
     * 导入唯一码
     * @param vm
     * @param files
     * @return
     */
    @PostMapping("/importCode")
    public JsonResult importCode(CodeVM vm, MultipartFile[] files) {
        lock.lock();
        log.info("测试:{}","11111111111111111111111111111111111111111111111111111");
        JsonResult result = new JsonResult();
        Integer type = vm.getType();
        Integer prizeGoodId = vm.getPrizeGoodId();
        try {
            if(files != null && files.length > 0 ) {
                List<PrizeCode>  codeList= new ArrayList<>();
                Date date =new Date();
                MultipartFile file = files[0];
                String name = file.getOriginalFilename();
                String suffix = name.substring(name.lastIndexOf(".") + 1);
                if(!"xlsx".equals(suffix) && !"xls".equals(suffix) ){
                    result.setState(-1);
                    result.setMessage("文件格式不正确，请上传正确格式的文件");
                    return result;
                }
                log.info("上传code:{}","--------------------------------------------------------------------------");
                log.info("文件全名originalFilename:{}",file.getOriginalFilename());
                List<Object> list = EasyExcelUtil.readExcel(file, new DwaConvertCodeModel(), 1, 1);
                List<String> existList =null;
                if (list != null && list.size() > 0) {
                   if(vm.getIsCheck() !=null){
                       if(vm.getIsCheck() ==1 ){
                           existList =uploadCodeService.findAllCode();
                       }
                   }
                    PrizeCode prizeCode = null;
                    for (Object o : list) {
                        DwaConvertCodeModel code = (DwaConvertCodeModel) o;
                        if(vm.getIsCheck() !=null) {
                            if (vm.getIsCheck() == 1) {
                                if (existList.contains(code.getCode())) {
                                    result.setState(-1);
                                    result.setMessage("导入数据与系统数据重复，请勿上传相同数据!");
                                    return result;
                                }
                            }
                        }
                        prizeCode =new PrizeCode();
                        prizeCode.setCode(code.getCode());
                        prizeCode.setActivityId(vm.getActivityId());
                        prizeCode.setIsUse(1);
                        prizeCode.setPrizeGoodId(prizeGoodId);
                        prizeCode.setCreateTime(date);
                        codeList.add(prizeCode);
                    }
                    Set<PrizeCode> stringSet=new HashSet<PrizeCode>(codeList);
                    //List<String> stringList = codeList.stream().map(PrizeCode::getCode)
                    //                        .collect(Collectors.toList());
                    //                    long count = stringList.stream().distinct().count();
                    if(vm.getIsCheck() !=null) {
                        if (vm.getIsCheck() == 1) {
                            if (stringSet.size() != codeList.size()) {
                                result.setState(-1);
                                result.setMessage("数据包中存在重复的券码，请检查数据后再上传!");
                                return result;
                            }
                        }
                    }
                    uploadCodeService.addAllCode(codeList,prizeGoodId,list.size());
//                    PrizeGood pd = prizeGoodService.findById();
//                    pd.setId(prizeGoodId);
//                    int stock = pd.getStock() == null ? 0 : pd.getStock();
//                    pd.setStock(stock+list.size());
//                    prizeGoodService.updatePrizeGood(pd);
//                    int totalCount =0;
//                    if(existList !=null){
//                        totalCount = codeList.size() + existList.size();
//                    }else{
//                        totalCount = codeList.size();
//                    }
                    result.setState(0);
                    result.setMessage("本次成功导入"+codeList.size()+"条数据");
                }
            }else{
                result.setState(-1);
                result.setMessage("上传文件不能为空!");
                return result;            }
        } catch (Exception e) {
            log.error("e:{}", e);
            result.setState(-1);
            result.setMessage("系统繁忙");
        }finally {
            lock.unlock();
        }
        return result;
    }

    /**
     * 导入唯一码
     * @return
     */
    @GetMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) {
        String fileName = "唯一码模板";
        String sheetName = "唯一码模板";
        List<CodeTemplateVm> userList = new ArrayList<>();
        try {
            ExcelUtil.writeExcel(response, userList, fileName, sheetName, CodeTemplateVm.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
